﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Controllers;

namespace Web
{
    public partial class PositionEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.Params["Id"] != null)
                {
                    int id = int.Parse(Request.Params["Id"]);
                    ApolloOaDataContext ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
                    Position model = ctx.Positions.Single(q => q.Id == id);
                    txtName.Text = model.Name;
                    txtDescription.Text = model.Description;
                    txtOrderNo.Text = model.OrderNo.ToString();
                    Id.Value = id.ToString();
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                ApolloOaDataContext ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
                Position model;

                if (string.IsNullOrWhiteSpace(Id.Value))
                {
                    model = new Position();
                    model.Name = txtName.Text.Trim();
                    model.Description = txtDescription.Text.Trim();
                    model.OrderNo = int.Parse(txtOrderNo.Text);
                    ctx.Positions.InsertOnSubmit(model);
                }
                else
                {
                    model = ctx.Positions.Single(q => q.Id == int.Parse(Id.Value));
                    model.Name = txtName.Text.Trim();
                    model.Description = txtDescription.Text.Trim();
                    model.OrderNo = int.Parse(txtOrderNo.Text);
                }
                ctx.SubmitChanges();
            }
            Response.Write("<script>window.returnValue='1';window.close();</script>");
        }
    }
}